package com.fujimana.rockincat.restree.message;

import java.text.MessageFormat;
import java.util.Locale;
import java.util.Map;

public class MessageRepository {

	private static ThreadLocal<Locale> currentLocale = new ThreadLocal<Locale>() {

		@Override
		protected Locale initialValue() {
			return Locale.getDefault();
		}
	};

	private Map<String, Message> repo;

	public MessageRepository(Map<String, Message> messages) {
		repo = messages;
	}

	public static void setCurrentLocale(Locale locale) {
		currentLocale.set(locale);
	}

	public static Locale getCurrentLocale() {
		return currentLocale.get();
	}

	public String getMessage(Enum<?> id, Object... args) {
		return getMessage(id, currentLocale.get(), args);
	}

	public String getMessage(Enum<?> id, Locale locale, Object... args) {
		String key = id.name();

		if (repo.containsKey(key) == false) {
			buildEnumMessage(new Message(), id, locale);
		}

		if (repo.get(key).isLocale(locale) == false) {
			buildEnumMessage(repo.get(key), id, locale);
		}

		return getMessage(key, locale, args);
	}

	private synchronized void buildEnumMessage(Message message, Enum<?> id, Locale locale) {
		String str = id.name();
		String key = id.name();
		
		com.fujimana.rockincat.restree.annotation.message.Message m = id
				.getClass()
				.getAnnotation(
						com.fujimana.rockincat.restree.annotation.message.Message.class);
		
		if(m != null) {
			str = m.value();
		}
		
		message.setId(key);
		message.setMesssage(str, locale);
	}

	public String getMessage(String id, Object... args) {
		return getMessage(id, currentLocale.get(), args);
	}

	public String getMessage(String id, Locale locale, Object... args) {

		Message message = repo.get(id);

		if (message == null) {
			return id;
		}

		String str = message.getMesssage(locale);

		if (str == null) {
			return id;
		}

		MessageFormat formater = new MessageFormat(str);

		return formater.format(args);
	}
}
